# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import time
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
import supeanut_config
from CommonLib.mylog import mylog
from CommonLib.db.MongoDBTool import MongoDBTool
from CommonLib.StockTool import StockTool


'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
	xxx
	xxxxx
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class DataClear:
	# init what
	def __init__(self):
		#self.param = supeanut_config.PARAM
		self.mongo = MongoDBTool()
		self.db_name = supeanut_config.MONGO_DB
		self.day_coll = supeanut_config.MONGO_COLL_DAYDATA
		self.stockTool = StockTool()
		
	# 日级日期对其
	def dayDateSyn(self, codes, with_del=False):
		self.mongo.conn(self.db_name, self.day_coll)
		# 拿到交易日历
		flag, cal_dates = self.stockTool.get_trade_date()
		# 删除比上证指数历史久远的数据
		self.mongo.coll.delete_one({u'code':u'sz000505', u'date':u'1992-12-20'})
		# 遍历code和index
		next_codes = []
		for code in codes:
			code_dates_iter = self.mongo.coll.find(filter={'code':code},projection=['date'])
			code_dates = []
			for code_date in code_dates_iter:
				code_dates.append(code_date['date'])
			if len(code_dates) == 0:
				#print code, 'code len is zero'
				continue
			code_dates.sort()
			code_date_s = code_dates[0]
			i = 0
			find_s_tag = False
			for cal_date in cal_dates:
				i += 1
				if cal_date == code_date_s:
					find_s_tag = True
					break
			if find_s_tag is False:
				print 'error in %s, not find s_date in cal dates'%code
			for j in range(0, len(code_dates)):
				cal_date = cal_dates[j+i-1]
				code_date = code_dates[j]
				if cal_date == code_date:
					continue
				elif cal_date > code_date:
					print '1. cal_date > code_date ,need del code_date',code, cal_date, code_date
					if with_del is True:
						self.mongo.coll.delete_one({'code':code,'date':code_date})
						next_codes.append(code)
					break
				else:
					#print 'cal_date < code_date ,maybe stop situ',code, cal_date, code_date
					k = 1
					tag = False
					while cal_date < code_date:
						cal_date = cal_dates[j+i-1+k]
						if cal_date == code_date:
							i += k
							tag = True
							break
						if cal_date > code_date:
							print '2. cal_date > code_date ,need del code_date',code, cal_date, code_date
							if with_del is True:
								self.mongo.coll.delete_one({'code':code,'date':code_date})
								next_codes.append(code)
							break
						k += 1
					if tag is False:
						break
					else:
						continue
		return next_codes

	def dayDateSynControl(self, with_del=True):
		flag, codes = self.stockTool.get_all_stand_codes()
		while len(codes) > 0:
			codes = self.dayDateSyn(codes, with_del)
					
			
if __name__ == '__main__':
	obj = DataClear()
	obj.dayDateSynControl(with_del=True)
